﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace PDFGenerator
{
    class PDFWriter
    {

        static public void PrintSalesReport(string[,] dataTable, string fileName)
        {
            Document document = new Document();
            PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
            document.Open();

            PdfPTable table = new PdfPTable(5);

            string[] headText = { "Product", "Quantity", "Unit Price", "Location", "Sum" };

            foreach (string cellText in headText)
            {
                Paragraph paragraph = new Paragraph(cellText);
                paragraph.Font.SetStyle(Font.BOLD);
                PdfPCell Cell1 = new PdfPCell(paragraph);
                Cell1.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY;
                table.AddCell(Cell1);
            }

            double totalSum = 0;

            for (int i = 0; i < dataTable.GetLength(0); i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    PdfPCell cell = new PdfPCell(new Paragraph(dataTable[i, j]));
                    if (j == 4)
                        totalSum += double.Parse(dataTable[i, j]);

                    table.AddCell(cell);

                }
            }

            for (int j = 1; j < 6; j++)
            {
                PdfPCell cell;
                if (j == 4)
                {
                    cell = new PdfPCell(new Paragraph("Total sum:"));
                    cell.HorizontalAlignment = 2;
                }
                else if (j == 5)
                {
                    Paragraph p = new Paragraph(totalSum.ToString());
                    p.Font.SetStyle(Font.BOLD);
                    cell = new PdfPCell(p);
                }
                else
                {
                    cell = new PdfPCell(new Paragraph(""));
                }

                if (j < 5)
                    cell.DisableBorderSide(Rectangle.RIGHT_BORDER);
                if (j > 1 && j < 5)
                    cell.DisableBorderSide(Rectangle.LEFT_BORDER);

                table.AddCell(cell);

            }

            document.Add(table);
            document.Close();

        }

        public static string[,] ConvertToString(List<Product> products)
        {
            string[,] str = new string[products.Count, 5];
            for (int r = 0; r < products.Count; r++)
            {
                str[r, 0] = products[r].Id;
                str[r, 1] = products[r].Quantity + " " + products[r].QType;
                str[r, 2] = products[r].Price;
                str[r, 3] = products[r].SpName;
                str[r, 4] = products[r].Sum;
            }

            return str;
        }

    }
}
